﻿using System;

namespace Outfish {

	/// <summary>
	/// Attched to the node you want, scans previous sibling since
	/// </summary>
	internal class HasPreviousSiblingSelector : INodeSelector {
	
		#region constructor
	
		public HasPreviousSiblingSelector( INodeSelector sibSelector, bool any ){
			this._sibSelector = sibSelector;
			this._any = any;
		}
	
		#endregion

		public bool IsMatch(HtmlNode node){
			
			int end = node.SiblingIndex;
			if( end == 0 ){ return false; }
			
			int i =  this._any ? 0 : end - 1;
			
			for(;i<end;++i){ 
				if( _sibSelector.IsMatch( node.ParentNode.ChildNodes[i] ) ){ 
					return true; 
				}
			}
			return false;
		}
		
		public override string ToString() {
			return _sibSelector.ToString() + (this._any ? "~" : "+" );
		}

		
		#region private fields
		
		bool _any; // true searches all previous, false searches immediate
		INodeSelector _sibSelector;
		
		#endregion
	}
}
